﻿using Microsoft.Phone.Controls;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using ShakeGestures;
using System;
using System.IO.IsolatedStorage;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Threading;

namespace A_larm_Shake
{
    public partial class page_clock : PhoneApplicationPage
    {
        private DateTime EndTime { get; set; }
        private DispatcherTimer dispatcherTimer;
        string descrip = "", spanx = "", lv = "";
        int count;
        string toggleValue;
        IsolatedStorageSettings tgvalue = IsolatedStorageSettings.ApplicationSettings;

        MessageBoxButton buttons = MessageBoxButton.OK;
        MessageBoxResult result;

        /*--------------------------------------------  --------------------------------------------*/

        #region main page
        public page_clock()
        {
            InitializeComponent();
            Loaded += page_clock_Loaded;

            BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/temp.png", UriKind.Relative));
            meter.Source = myBitmapImage;

            string str = null;
            str = String.Format("{0:D2}:{1:D2}",
                               EndTime.Hour, EndTime.Minute);

            DispatcherTimer timer = new DispatcherTimer();
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();

            this.EndTime = DateTime.MinValue;
            this.timeSpan.Value = TimeSpan.FromSeconds(0);
            this.chk_eh.Text = str;

            PhoneApplicationService.Current.ApplicationIdleDetectionMode = IdleDetectionMode.Disabled;
            PhoneApplicationFrame rootFrame = App.Current.RootVisual as PhoneApplicationFrame;

            
        }
        #endregion

        #region OnLoad
        private void page_clock_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            if (IsolatedStorageSettings.ApplicationSettings.Contains("AlarmData1"))
            {
                spanx =
                IsolatedStorageSettings.ApplicationSettings["AlarmData1"] as string;
                lv =
                IsolatedStorageSettings.ApplicationSettings["AlarmData2"] as string;
                descrip =
                IsolatedStorageSettings.ApplicationSettings["AlarmData3"] as string;

                if (IsolatedStorageSettings.ApplicationSettings.Contains("value1"))
                {
                    toggleValue =
                    IsolatedStorageSettings.ApplicationSettings["value1"] as string;
                }
                this.tg_val.Text = toggleValue;
            }

            if (toggleValue != null)
            {
                if (toggleValue == "on")
                {
                    this.EndTime = DateTime.MinValue + TimeSpan.Parse(spanx);

                    tg.IsChecked = true;
                    if (EndTime.Hour == DateTime.Now.Hour)
                    {
                        if (EndTime.Minute <= DateTime.Now.Minute)
                        {
                            tg.IsEnabled = false;

                            this.mesound.Play();
                            this.mesound.MediaEnded += new RoutedEventHandler(mediaElement1_MediaEnded);
                            sys_warn();

                            ShakeGesturesHelper.Instance.ShakeGesture +=
                                    new EventHandler<ShakeGestureEventArgs>(Instance_ShakeGesture);
                            ShakeGesturesHelper.Instance.MinimumRequiredMovesForShake = 4;
                            ShakeGesturesHelper.Instance.Active = true;
                        }
                    }
                }
                if (toggleValue == "off") 
                {
                    tg.IsChecked = false;
                }
            }

            if (lv == "1" || lv == "2" || lv == "3")
            {
                tg.IsEnabled = true;
            }
            else
            {
                tg.IsEnabled = false;
            }
        }
        #endregion

        /*--------------------------------------------  --------------------------------------------*/

        #region OnClick Button
        private void new_alarm_Click(object sender, System.EventArgs e)
        {
            // TODO: Add event handler implementation here.
            NavigationService.Navigate(new Uri("/page_setAlarm.xaml", UriKind.Relative));
        }

        private void switch_Checked(object sender, RoutedEventArgs e)
        {
            startalarm();

            if (ScheduledActionService.Find("AlarmShake") != null)
                ScheduledActionService.Remove("AlarmShake");

            Alarm a = new Alarm("AlarmShake");
            a.Content = "Go to A-larm Shake Now !!!";
            a.Sound = new Uri("Assets/alarm_sound.mp3", UriKind.Relative);
            a.BeginTime = DateTime.MinValue + TimeSpan.Parse(spanx);
            a.ExpirationTime = DateTime.Now.AddDays(7);
            a.RecurrenceType = RecurrenceInterval.Daily;

            ScheduledActionService.Add(a);

            if (ScheduledActionService.Find("testreminder") != null)
                ScheduledActionService.Remove("testreminder");

            Reminder r = new Reminder("testreminder");
            r.Title = "A-larm Shake Reminder";
            r.Content = "Click here to shake";
            r.NavigationUri = new Uri("/page_clock.xaml", UriKind.Relative);
            r.BeginTime = DateTime.MinValue + TimeSpan.Parse(spanx);
            r.ExpirationTime = DateTime.Now.AddDays(7);
            r.RecurrenceType = RecurrenceInterval.Daily;

            ScheduledActionService.Add(r);
            tg_val.Text = EndTime.Hour.ToString() + ":" + EndTime.Minute.ToString();
            
        }

        private void switch_Unchecked(object sender, RoutedEventArgs e)
        {
            stopalarm();

            if (ScheduledActionService.Find("AlarmShake") != null)
                ScheduledActionService.Remove("AlarmShake");
            
            if (ScheduledActionService.Find("testreminder") != null)
                ScheduledActionService.Remove("testreminder");
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            //this.NavigationService.RemoveBackEntry();
            if (!tgvalue.Contains("value1"))
            {
                tgvalue.Add("value1", toggleValue);
            }
            else
            {
                tgvalue["value1"] = toggleValue;
            }
            tgvalue.Save();
            base.OnBackKeyPress(e);
        }

        #endregion

        /*--------------------------------------------  --------------------------------------------*/

        #region Start stop run 
        public void startalarm()
        {
            tbx2.Text = lv;
            
            if (this.dispatcherTimer == null)
            {
                this.dispatcherTimer = new DispatcherTimer();
                this.dispatcherTimer.Interval = TimeSpan.FromMilliseconds(100);
                this.dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
            }

            if (this.EndTime == DateTime.Now)
            {
                this.EndTime = DateTime.Now + TimeSpan.Parse(spanx);
            }

            toggleValue = "on";

            this.dispatcherTimer.Start();

            if (!tgvalue.Contains("value1"))
            {
                tgvalue.Add("value1", toggleValue);
            }
            else
            {
                tgvalue["value1"] = toggleValue;
            }
        }

        public void stopalarm()
        {
            this.dispatcherTimer.Stop();
            this.EndTime = DateTime.Now;
            this.timeSpan.Value = TimeSpan.FromSeconds(0);
            count = 0;
            ShakeGesturesHelper.Instance.Active = false;
            tbx2.Text = "";
            toggleValue = "off";

            if (!tgvalue.Contains("value1"))
            {
                tgvalue.Add("value1", toggleValue);
            }
            else
            {
                tgvalue["value1"] = toggleValue;
            }
        }

        #endregion

        #region Timer
        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            this.EndTime = DateTime.Now;
            base.OnNavigatedFrom(e);
        }

        void timer_Tick(object sender, EventArgs e)
        {
            DateTime dt = DateTime.Now;

            chk_nh.Text = dt.ToString("HH:mm:ss");
        }

        void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            string str = null;
            str = String.Format("{0:D2}:{1:D2}",
                               EndTime.Hour, EndTime.Minute);


            this.EndTime = DateTime.MinValue + TimeSpan.Parse(spanx);

            this.chk_eh.Text = str;

            if (EndTime.Hour == DateTime.Now.Hour)
            {
                if (EndTime.Minute == DateTime.Now.Minute)
                {
                    this.mesound.Play();
                    this.mesound.MediaEnded += new RoutedEventHandler(mediaElement1_MediaEnded);
                    sys_warn();

                    ShakeGesturesHelper.Instance.ShakeGesture +=
                            new EventHandler<ShakeGestureEventArgs>(Instance_ShakeGesture);
                    ShakeGesturesHelper.Instance.MinimumRequiredMovesForShake = 4;
                    ShakeGesturesHelper.Instance.Active = true;
                }
            }
        }
        #endregion

        #region Alert System
        private void sys_warn()
        {
            this.dispatcherTimer.Stop();
            tg.IsEnabled = false;
        }

        private void testx()
        {
            string message = "Time Out !!!";
            //stop sound here
            this.mesound.Stop();
            ShakeGesturesHelper.Instance.Active = false;
            result = MessageBox.Show(descrip, message, buttons);
            count = 0;
            tg.IsEnabled = true;
            tg.IsChecked = false;

            BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/temp.png", UriKind.Relative));
            meter.Source = myBitmapImage;
        }

        public double remainingHour { get; set; }

        void mediaElement1_MediaEnded(object sender, RoutedEventArgs e)
        {
            mesound.Play();
        }

        #endregion

        #region chk LV
        void Instance_ShakeGesture(object sender, ShakeGestureEventArgs e)
        {
            tbx3.Dispatcher.BeginInvoke(() =>
            {
                // start sound here
                if (lv == "1")
                {
                    if (count < 20)
                    {
                        count++;
                        meterchk();
                    }
                    else
                    {
                        testx();
                    }
                }
                else if (lv == "2")
                {
                    if (count < 30)
                    {
                        count++;
                        meterchk2();
                    }
                    else
                    {
                        testx();
                    }
                }
                else if (lv == "3")
                {
                    if (count < 40)
                    {
                        count++;
                        meterchk3();
                    }
                    else
                    {
                        testx();
                    }
                }
            });
        }
        #endregion

        /*--------------------------------------------  --------------------------------------------*/

        #region meter LV1 20t
        private void meterchk()
        {
            if (count <= 1)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/2.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 2)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/4.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 4)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/6.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 6)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/8.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 8)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/10.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 10)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/12.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 12)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/14.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 15)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/16.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 18)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/17.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
        }
        #endregion

        #region meter LV2 30t
        private void meterchk2()
        {
            if (count <= 1)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/2.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 3)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/4.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 4)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/6.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 6)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/8.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 8)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/9.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 10)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/10.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 12)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/11.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 15)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/12.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 18)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/13.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 20)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/14.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 22)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/15.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 24)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/16.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 28)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/17.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
        }
        #endregion

        #region meter LV3 40t
        private void meterchk3()
        {
            if (count <= 1)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/2.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 3)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/4.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 6)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/6.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 9)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/8.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 12)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/9.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 15)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/10.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 18)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/11.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 21)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/12.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 24)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/13.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 27)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/14.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 30)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/15.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 33)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/16.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 36)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/17.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
        }
        #endregion

        /*--------------------------------------------  --------------------------------------------*/
        
      }
    }
